package com.infore.dataReceiving.outsideInterface.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.infore.dataReceiving.constant.Constants;
import com.infore.dataReceiving.dto.WaterInstructionsDataDto;
import com.infore.dataReceiving.enums.ResultStatus;
import com.infore.dataReceiving.enums.WaterQualityTargetLevel;
import com.infore.dataReceiving.externalInterface.siteManage.ISiteManageService;
import com.infore.dataReceiving.outsideInterface.service.IHourDataService;
import com.infore.dataReceiving.select.dto.QueryParamDto;
import com.infore.dataReceiving.select.util.QueryCondition;
import com.infore.dataReceiving.service.IInstructionsService;
import com.infore.dataReceiving.util.JsonUtils;
import com.infore.dataReceiving.util.Page;
import com.infore.dataReceiving.util.ResultEntity;
import com.infore.dataReceiving.util.WaterQualityUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 小时数据信息外部接口
 * @author liulefa
 *
 */
@Api(value = "小时数据信息外部接口", tags = {"小时数据信息外部接口" })
@RestController
@RequestMapping("/HourDataController")
public class HourDataController {
	@Autowired
	private IHourDataService iHourDataServices;
	@Autowired
    private IInstructionsService iInstructionsService;
    
    @Autowired
    private ISiteManageService iSiteManageService;
	
	@ApiOperation(value = "获取实时数据", notes = "获取实时数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "mn", value = "站点mn号", paramType = "query", required = true, dataType = "String"),
         @ApiImplicitParam(name = "isNnusual", value = "是否查看异常数据all全部数据，unusual异常数据，normal正常数据", paramType = "query", required = true, dataType = "String"),
        @ApiImplicitParam(name = "pageNum", value = "第几页", paramType = "query", required = true, dataType = "String"),
        @ApiImplicitParam(name = "pageSize", value = "每页多少条记录", paramType = "query", required = true, dataType = "String")
    })
    @RequestMapping(value = "/queryRowToColRealTimeData", method = RequestMethod.GET)
    @ResponseBody
    public ResultEntity queryRealTimeData(String mn,String pageNum,String pageSize,String isNnusual) throws Exception {
//	    SimpleDateFormat sdm=new SimpleDateFormat("yyyy年MM月dd日 HH点:mm分:ss:秒");
//        String format = sdm.format(new Date());
//        System.out.println("当前时间"+format);
        Calendar c = Calendar.getInstance();
        Date endTime = new Date();
        c.setTime(endTime);
        c.add(Calendar.DAY_OF_MONTH, -30);
        List<Map<String, Object>> list = iInstructionsService.queryRowToColRealTimeData(c.getTime(), endTime,mn,pageNum,pageSize);
//        format = sdm.format(new Date());
//        System.out.println("当前时间"+format);
        QueryParamDto queryParamDto = JsonUtils.readJsonFromClassPath("/queryParam/siteQuery.json", QueryParamDto.class);
        QueryCondition q = new QueryCondition();
        String mnList = "stationMn", oper ="in";
        q.setOperator(Arrays.asList(oper));
        q.setProperty(Arrays.asList(mnList));
        q.setContent(Arrays.asList(mn));
        queryParamDto.setQueryCondition(q);
        ResultEntity resultEntity = iSiteManageService.queryStation(queryParamDto);
        Map<String, Object> dataMap = (Map<String, Object>)resultEntity.getContent();
        List<Map<String, Object>> siteList = (List<Map<String, Object>>)dataMap.get("dataList");
        Map<String, Map<String, Object>> siteMap = new HashMap<>();
        for(Map<String, Object> map:siteList) {
            siteMap.put(map.get("stationMn").toString(), map);
        }
        List<WaterInstructionsDataDto> unualList = new ArrayList<>();
        List<WaterInstructionsDataDto> normalList = new ArrayList<>();
        List<WaterInstructionsDataDto> finalList = new ArrayList<>();
        SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(Map<String, Object> map:list) {
            String mns = map.get("mn").toString();
            List<WaterInstructionsDataDto> dtoList = new ArrayList<WaterInstructionsDataDto>();
            WaterInstructionsDataDto waterInstructionsDataDto = new WaterInstructionsDataDto();
            String provinceName = siteMap.get(mns).get("provinceId_areaName") == null ? "" : siteMap.get(mns).get("provinceId_areaName").toString();
            waterInstructionsDataDto.setProvince(provinceName);
            waterInstructionsDataDto.setBasin(siteMap.get(mns).get("basinn_basinnName").toString());
            waterInstructionsDataDto.setStationName(siteMap.get(mns).get("stationName").toString());
            waterInstructionsDataDto.setCityName(siteMap.get(mns).get("cityName")==null?null:siteMap.get(mns).get("cityName").toString());
            waterInstructionsDataDto.setAreaName(siteMap.get(mns).get("areaName")==null?null:siteMap.get(mns).get("areaName").toString());
            String targerWaterQuality = siteMap.get(mns).get("targerWaterQuality") == null ? "-" : siteMap.get(mns).get("targerWaterQuality").toString();
            //          if("40000000000001".equals(mns)) {
//              waterInstructionsDataDto.setStationName("水站1");
//          }else if("40000000000002".equals(mns)) {
//              waterInstructionsDataDto.setStationName("水站2");
//          }else if("40000000000003".equals(mns)) {
//              waterInstructionsDataDto.setStationName("污染源站点1");
//          }else {
//              waterInstructionsDataDto.setStationName("测试站");
//          }
            waterInstructionsDataDto.setTargerWaterQuality(targerWaterQuality);
            waterInstructionsDataDto.setMn(map.get("mn")==null?null:map.get("mn").toString());
            waterInstructionsDataDto.setDataTime(sdfDateFormat.format((Date)map.get("dataTime")));
            waterInstructionsDataDto.setStationState("0");
            String w01010 = map.get("w01010")==null?null:map.get("w01010").toString();  //水温
            String w01001 = map.get("w01001")==null?null:map.get("w01001").toString(); //pH值"
            String w01009 = map.get("w01009")==null?null:map.get("w01009").toString();;  //溶解氧"
            String w01003 = map.get("w01003")==null?null:map.get("w01003").toString();;  //浑浊度"
            String w01014 = map.get("w01014")==null?null:map.get("w01014").toString();;  //电导率"
            String w01019 = map.get("w01019")==null?null:map.get("w01019").toString();;  //高锰酸盐指数
            String w21003 = map.get("w21003")==null?null:map.get("w21003").toString();;  //氨氮
            String w21011 = map.get("w21011")==null?null:map.get("w21011").toString();;  //总磷
            String w21001 = map.get("w21001")==null?null:map.get("w21001").toString();;  //总氮
            String w01018 = map.get("w01018")==null?null:map.get("w01018").toString();;  //CODcr
            String w01016 = map.get("w01016")==null?null:map.get("w01016").toString();;  //叶绿素
            //waterInstructionsDataDto.setWaterQuality("1");
            waterInstructionsDataDto.setW01010(w01010);
            waterInstructionsDataDto.setW01001(w01001);
            waterInstructionsDataDto.setW01009(w01009);
            waterInstructionsDataDto.setW01003(w01003);
            waterInstructionsDataDto.setW01014(w01014);
            waterInstructionsDataDto.setW01019(w01019);
            waterInstructionsDataDto.setW21003(w21003);
            waterInstructionsDataDto.setW21011(w21011);
            waterInstructionsDataDto.setW21001(w21001);
            waterInstructionsDataDto.setW01018(w01018);
            waterInstructionsDataDto.setW01016(w01016);
            dtoList.add(waterInstructionsDataDto);
            //判断单个因子是不是超标
            //暂时单个因子的超标等级限制为三级
            int singlLevel = 3;
            String w01010State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w01010", w01010), singlLevel);
            String w01001State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w01001", w01001), singlLevel);
            String w01009State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w01009", w01009), singlLevel);
            String w01003State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w01003", w01003), singlLevel);
            String w01014State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w01014", w01014), singlLevel);
            String w01019State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w01019", w01019), singlLevel);
            String w21003State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w21003", w21003), singlLevel);
            String w21011State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w21011", w21011), singlLevel);
            String w21001State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w21001", w21001), singlLevel);
            String w01018State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w01018", w01018), singlLevel);
            String w01016State = WaterQualityUtil.OverData(WaterQualityUtil.getWaterLevel("w01016", w01016), singlLevel);
            waterInstructionsDataDto.setW01001State(w01001State);
            waterInstructionsDataDto.setW01003State(w01003State);
            waterInstructionsDataDto.setW01009State(w01009State);
            waterInstructionsDataDto.setW01010State(w01010State);
            waterInstructionsDataDto.setW01014State(w01014State);
            waterInstructionsDataDto.setW01016State(w01016State);
            waterInstructionsDataDto.setW01018State(w01018State);
            waterInstructionsDataDto.setW01019State(w01019State);
            waterInstructionsDataDto.setW21001State(w21001State);
            waterInstructionsDataDto.setW21003State(w21003State);
            waterInstructionsDataDto.setW21011State(w21011State);
            //计算综合水质等级
            WaterQualityUtil.setWaterQuality(dtoList);
            String level = waterInstructionsDataDto.getWaterQuality();
            String flag = "normal";
            //判断整条记录是不是超标数据
            if(NumberUtils.isNumber(level)) {
                String arm = WaterQualityTargetLevel.getDesc(targerWaterQuality).getStatusCode();//目标水质等级
                int armLevel = NumberUtils.createInteger(arm);
                int levelInt = NumberUtils.createInteger(level);//实际等级
                flag = levelInt > armLevel ? "unusual":"normal";
                waterInstructionsDataDto.setIsNnusual(flag);
            }
            if ("unusual".equals(flag)) {
                unualList.add(waterInstructionsDataDto);
            } else if("normal".equals(flag)){
                normalList.add(waterInstructionsDataDto);
            }
            finalList.add(waterInstructionsDataDto);
        }
        if ("unusual".equals(isNnusual)) {
            finalList = unualList;
        } else if("normal".equals(isNnusual)){
            finalList = normalList;
        }
        int count = iInstructionsService.queryRowToColRealTimeDataCount(mn);
        int yu = count/Integer.valueOf(pageSize);
        int mo = count%Integer.valueOf(pageSize);
        if(mo>0) {
            yu+=1;
        }
        
        Page<WaterInstructionsDataDto> page = new Page<WaterInstructionsDataDto>();
        page.setList(finalList);
        page.setPageNo(Integer.valueOf(pageNum));
        page.setPageSize(Integer.valueOf(pageSize));
        page.setTotalPages(yu);
        page.setTotalRecords(count);
        
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setPage(page);
    }
	

	@ApiOperation(value="小时数据信息外部接口",tags="小时数据信息外部接口")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "stationCode", value = "站点编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "factorCode", value = "因子参数编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", required = true, dataType = "String"),
	})
	@PostMapping(value = "/queryHourDatas")
	public ResultEntity queryHourDatas(String stationCode,String factorCode,String startTime,String endTime){
		return iHourDataServices.queryHourDatas(stationCode,factorCode,startTime,endTime);
	}
	
	@ApiOperation(value="小时数据信息外部接口--单点自动站",tags="小时数据信息外部接口--单点自动站")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "stationCode", value = "站点编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "factorCode", value = "因子参数编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", required = true, dataType = "String"),
	})
	@PostMapping(value = "/audioSingReport")
	public ResultEntity audioSingReport(String stationCode,String factorCode,String startTime,String endTime){
		return iHourDataServices.audioSingReport(stationCode,factorCode,startTime,endTime);
	}
	
	@ApiOperation(value="小时数据信息外部接口--单点自动站",tags="小时数据信息外部接口--多点自动站")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "stationCode", value = "站点编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "factorCode", value = "因子参数编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", required = true, dataType = "String"),
	})
	@PostMapping(value = "/audioMoreReport")
	public ResultEntity audioMoreReport(String stationCode,String factorCode,String startTime,String endTime){
		return iHourDataServices.audioMoreReport(stationCode,factorCode,startTime,endTime);
	}
	
	@ApiOperation(value="实时数据分组",tags="实时数据实时数据分组")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "stationCode", value = "站点编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "factorCode", value = "因子参数编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", required = true, dataType = "String"),
	})
	@PostMapping(value = "/realDataGroup")
	public ResultEntity realDataGroup(String stationCode,String factorCode,String startTime,String endTime){
		return iHourDataServices.realDataGroup(stationCode,factorCode,startTime,endTime);
	}
	
	@ApiOperation(value="实时数据不分组",tags="不分组")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "stationCode", value = "站点编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "factorCode", value = "因子参数编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", required = true, dataType = "String"),
	})
	@PostMapping(value = "/realData")
	public ResultEntity realData(String stationCode,String factorCode,String startTime,String endTime){
		return iHourDataServices.realData(stationCode,factorCode,startTime,endTime);
	}
	
	
	@ApiOperation(value = "获取日数据", notes = "获取日数据")
    @RequestMapping(value = "/getDayData", method = RequestMethod.GET)
    @ResponseBody
    public ResultEntity getDayData() {
        return iHourDataServices.getDayData();
    }
    
    @ApiOperation(value = "更新小时数据标识", notes = "更新小时数据标识")
    @RequestMapping(value = "/updateHourFlag", method = RequestMethod.GET)
    @ResponseBody
    public ResultEntity updateHourFlag() {
        return iHourDataServices.updateFlag();
    }
    
    @ApiOperation(value = "获取未统计周数据时间", notes = "获取未统计周数据时间")
    @RequestMapping(value = "/getUnStatisticsWeekDataTime", method = RequestMethod.GET)
    @ResponseBody
    public ResultEntity getUnStatisticsWeekDataTime() {
        return iHourDataServices.getUnStatisticsWeekDataTime();
    }
    
    @ApiOperation(value = "获取未统计月数据时间", notes = "获取未统计月数据时间")
    @RequestMapping(value = "/getUnStatisticsMonthDataTime", method = RequestMethod.GET)
    @ResponseBody
    public ResultEntity getUnStatisticsMonthDataTime() {
        return iHourDataServices.getUnStatisticsMonthDataTime();
    }
    
    @ApiOperation(value = "获取未统计季度数据时间", notes = "获取未统计季度数据时间")
    @RequestMapping(value = "/getUnStatisticsQuarterDataTime", method = RequestMethod.GET)
    @ResponseBody
    public ResultEntity getUnStatisticsQuarterDataTime() {
        return iHourDataServices.getUnStatisticsQuarterDataTime();
    }
    
    @ApiOperation(value = "获取未统计年数据时间", notes = "获取未统计年数据时间")
    @RequestMapping(value = "/getUnStatisticsYearDataTime", method = RequestMethod.GET)
    @ResponseBody
    public ResultEntity getUnStatisticsYearDataTime() {
        return iHourDataServices.getUnStatisticsYearDataTime();
    }
}
